package com.jswdwsx.esign.config

import com.jswdwsx.esign.util.RedisUtil
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.data.redis.RedisProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.connection.RedisPassword
import org.springframework.data.redis.connection.RedisStandaloneConfiguration
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.core.StringRedisTemplate

@Configuration
class RedisConfig(private val redisProperties: RedisProperties) {

    @Bean
    fun redisTemplate(redisConnectionFactory: RedisConnectionFactory): RedisTemplate<String, Any> {
        val template = RedisTemplate<String, Any>()
        initRedisTemplate(template, redisConnectionFactory)
        return template
    }

    @Bean("redisConnectionFactory")
    fun redisConnectionFactory(): RedisConnectionFactory {
        return getRedisConnectionFactory(redisProperties.database, redisProperties.host, redisProperties.password)
    }

    @Bean
    @ConditionalOnMissingBean
    fun stringRedisTemplate(redisConnectionFactory: RedisConnectionFactory): StringRedisTemplate {
        val template = StringRedisTemplate()
        template.setConnectionFactory(redisConnectionFactory)
        return template
    }

    @Bean(name = ["redisUtil"])
    fun redisUtil(redisTemplate: RedisTemplate<String, Any>): RedisUtil {
        return RedisUtil(redisTemplate)
    }

    private fun getRedisConnectionFactory(database: Int, host: String, password: String): RedisConnectionFactory {
        val redisStandaloneConfiguration = RedisStandaloneConfiguration()
        redisStandaloneConfiguration.database = database
        redisStandaloneConfiguration.hostName = host
        redisStandaloneConfiguration.password = RedisPassword.of(password)
        return LettuceConnectionFactory(redisStandaloneConfiguration)
    }

    /**
     * 设置数据存入 redis 的序列化方式,并开启事务
     */
    private fun initRedisTemplate(redisTemplate: RedisTemplate<String, Any>, factory: RedisConnectionFactory) {
        // 开启事务
        redisTemplate.setEnableTransactionSupport(true)
        redisTemplate.setConnectionFactory(factory)
    }
}
